import traceback
import json
import io
import time
import requests
from copy import deepcopy

from django.conf import settings
from django.core.files import File
from django.utils.module_loading import import_string

from common import DINGTALK_CORP_ID, DINGTALK_BASE_URL, AgentId
from common.ding_client import DingClient
from config.settings.base import logger
from account.models import User
from account.serializers import FetchAccountUserSerializer


class SendMsg(object):
    """
    发送钉钉卡片消息
    """
    # 卡片格式列表
    _CARD_MAP = {
        1: {
            "msgtype": "action_card",
            "action_card": {
                "title": "工单抄送！",
                "btn_orientation": "1",
            }
        },
        2: {
            "msgtype": "action_card",
            "action_card": {
                "title": "审批",
                "btn_orientation": "1",
            }
        },
    }

    @classmethod
    def send_cc(cls, cc, workflow_id=None):
        """
        抄送发消息
        :return:
        """
        card_params = {
            "markdown": """# **howflow**\n  ## 您有新的工单抄送，请注意查收""",
            "btn_json_list": [
                {
                    "title": "查看抄送工单",
                    "action_url": "{}#/TicketDetails?ticket_id={}&workflow_id={}".format(
                        DINGTALK_BASE_URL, cc.ticket_id, workflow_id)
                },
            ]
        }
        return cls.send([cc.username, ], 1, card_params)

    @classmethod
    def send_at_msg(cls, username, ticket_id, textarea_value, ticket_creator, workflow_name, comment_creator):
        """
        评论时发送消息给@到的人
        :return:
        """
        card_params = {
            "markdown": """# **howflow**\n  ## {}在{}提交的{}审批里提到了您\n 评论内容：{}""".format(
                comment_creator, ticket_creator, workflow_name, textarea_value),
            "btn_json_list": [
                {
                    "title": "查看审批",
                    "action_url": "{}#/TicketDetails?ticket_id={}&workflow_name={}".format(
                        DINGTALK_BASE_URL, ticket_id, workflow_name)
                },
            ]
        }
        return cls.send([username, ], 2, card_params)

    @classmethod
    def send_print(cls, username, media_url):
        """
        打印发消息
        :return:
        """
        # todo 目前钉钉暂不支持前端直接上传，媒体文件， 此处暂由后端上传
        media_key = media_url.split('media/')[-1]
        file_name = '{}_{}.pdf'.format(username[:8], int(time.time()))
        content = requests.get(media_url, timeout=10).content
        output = io.BytesIO(content)
        media_file = File(output, file_name)
        client = DingClient()
        ret = client.message.media_upload('file', media_file)
        media_id = ret['media_id']
        card_params = {
            "msgtype": "file",
            "file": {
                "media_id": media_id
            }
        }
        ret = client.message.send(AgentId, card_params, touser_list=[username, ])
        storage = import_string(settings.DEFAULT_FILE_STORAGE)()
        storage.delete(media_key)
        return ret

    @classmethod
    def send(cls, send_users, card_code, card_params=None):
        """
        :param send_users:  用户username列表-->['admin', 'LiSi']
        :param card_code:  消息卡片类别
        :param card_params: 卡片内容参数
        :return:
        """
        msg_status = False
        if not settings.DEBUG:
            try:
                assert card_code and send_users
                msg_body = deepcopy(cls._CARD_MAP[card_code])
                if isinstance(card_params, dict):
                    msg_body['action_card'].update(card_params)
                client = DingClient()
                client.message.send(AgentId, msg_body, touser_list=send_users)
                msg_status = True
            except Exception as e:
                logger.info(card_code, send_users)
                logger.error(traceback.format_exc())
            return msg_status


def filter_field_list(field_list):
    """
    工单字段信息列表 过滤处理
    :param field_list: 工单字段信息列表
    :return:
    """
    for field_info in field_list:
        if field_info['field_type_id'] == 60:  # 单选用户名
            field_value = field_info['field_value']
            if field_value:
                user_qs = User.objects.filter(username=field_value)
                if user_qs.exists():
                    user = user_qs.first()
                    field_info['field_value'] = FetchAccountUserSerializer(user).data
                else:
                    field_info['field_value'] = {
                        "username": field_value,
                        "mobile": "",
                        "email": "",
                        "alias": ""}
        elif field_info['field_type_id'] == 70:   # 多选的用户名
            field_value = field_info['field_value']
            if field_value:
                users = json.loads(field_value.replace('\'', '\"'))
                user_qs = User.objects.filter(username__in=users)
                field_info['field_value'] = FetchAccountUserSerializer(user_qs, many=True).data
    return field_list
